// pages/category/category.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    //定义数组用来储存获取到的商品数据
    list: '',
    detail: '',
    name: '',
    canCoupon:0,
    //定义数组用来储存变量方便页面展示
    // dataDetail: '',
    //定义变量用来储存二级页面传递数据
    type: '',
    mealList: [],
    //监听输入框商品数量数据
    inputValue: 1,
    // 初始化隐藏样式
    hidden: true,
    hiddens: false,
    id: 2,
    week:'',
    inventory: 0,
    //定义一个变量用来储存价格
    price: 0,
    prices: 0,
    Totalprice:0,
    popupBottom: -100,
    setMenu:[],
    setMenus:'',
    //初始化动画图像
    animation: {},
    //背景隐藏
    hidden_bg: true,
    categoriesId:'',
    //储存购物车数据
    cart: '',
    //定义一个变量用来储存徽章的数
    gj_item: 0,
    //定义一个条件判断购物车中是否有数据
    condition: false,
    //定义一个变量用来储存门店ID
    storeID: 0,
    //定义一个变量用来储存用户id
    user_id: 0,
    type: null,
    videoUrl: '',
    taoc: '',
    detail: null, // 视频链接
    imageUrl: 'https://199shq.com/api/common/download',
    z_index: -1,
    showVideo: false,
    //储存分销二维码地址
    getQRCode: "",
    erweima: false,
    mendian: [],
    popupBottom: -200, // 弹出窗口初始位置（负值表示隐藏在页面底部）
    popupHeight: 0, // 弹出窗口初始高度（0表示隐藏）
    showMask: false, // 是否为遮罩层
    // 处理图标显示
    iconSize: 50,
    iconColor: 'red',
    iconType: 'cancel',
    voucherText: [], // 初始化为空数组 券 3个
    discountPrice: '',
    // 用户评价内容
    orderList: [],
    numberList: [],
    leng: 0,
    percent: 0,
    popupVisible: false, //用来控制弹窗购物车图片显示 
    productList: [],
    show: false,
    specification: false,
    viey: true,
    productStatus: '',
    categoriesId: '',
    mealType: '',
    dayOfWeek: '',
    displayList: [], // 用于显示的列表（含复制项）
    currentIndex: 0,
    currentOffset: 0,
    itemHeight: 80,
    interval: 3000,
    timer: null,
    isLoading: true,
    specMultipleValue: '',
    specMultiple: '',
    checks: [
      //   namePlus: '1*1',
      // //   value: '0',
      // //   checked: false
      // },
      // {
      //   namePlus: '2*2',
      // //   value: '1',
      // //   checked: false
      // },
      // {
      //   namePlus: '3*3',
      // //   value: '2',
      // //   checked: false
      // }
      // 更多规格...
    ],
    checksPlus: [],
    titleFontSize: 28, //默认字体大小
  },
  preventTouchMove() {
    console.log('今日')
    return true;
  },
  //调整字体大小自适应
  onLoad() {
  },
  onReady() {
    this.adjustTextSize();
  },
  adjustTextSize() {
    const query = this.createSelectorQuery();
    const maxContainerHeight = 130; // 单位 rpx
    const maxFontSize = 28; // 最大字体大小（px）
    const minFontSize = 12; // 最小字体大小（px）
    const lines = 2; // 预计最多允许显示 2 行

    const textElement = query.select('#product-title');

    textElement.fields({
      node: true,
      size: true
    }, (res) => {
      if (!res || !res.node) return;

      const {
        node
      } = res;
      const context = node.getContext('2d');
      const text = node.dataset.text;

      // 计算单行高度（以最大字体为准）
      context.font = `${maxFontSize}px sans-serif`;
      const singleLineHeight = maxFontSize * 1.2; // 行高约为字体大小的 1.2 倍

      // 总允许高度（px），130rpx 转换为 px（1rpx = 0.5px）
      const maxHeightInPx = maxContainerHeight * 0.5;

      // 总允许行数
      const allowedLines = Math.floor(maxHeightInPx / singleLineHeight);

      // 分割文本为多行（根据容器宽度估算，这里假设每行大约能容纳 18 个字）
      const wordsPerLine = 18; // 可根据实际宽度更精确计算
      const linesNeeded = Math.ceil(text.length / wordsPerLine);

      let finalFontSize = maxFontSize;

      if (linesNeeded > allowedLines) {
        // 如果需要的行数大于允许的最大行数，则缩放字体
        finalFontSize = Math.max(
          minFontSize,
          (allowedLines / linesNeeded) * maxFontSize
        );
      }

      this.setData({
        titleFontSize: finalFontSize,
      });
    }).exec();
  },

  //规格
  clicks: function (e) {
    //获取被点击的label标签上的data-index的属性值
    let index = e.currentTarget.dataset.index;
    //数据对象中的 checks 数组,包含了复选框当前状态
    let arrs = this.data.checks;
    let arrsPlus = this.data.checksPlus;
    //判断被点击的复选框是否未被选中
    if (arrs[index].checked == false) {
      arrs[index].checked = true;
      arrsPlus = [...arrs];
      console.log(arrsPlus);
    } else {
      arrs[index].checked = false;
    }
    // console.log(arrs); 
    //更新数组中的数据，保证数据的一个同步
    this.setData({
      checks: arrs,
      checksPlus: arrsPlus
    })
  },

  // 点击弹窗中的关闭按钮关闭弹窗
  closePopup(e) {
    var that = this;
    console.log("窗口关闭点击事件已触发");
    that.setData({
      show: false,
      inputValue: 1,

    });
    //关闭窗口后，商品数量清零

  },
  //点击阴影部分弹窗关闭
  // closemodel: function(){
  //     this.closePopup();
  // },
  // 跳转商品评分
  evaluateContent: function () {
    const type = this.data.type
    wx.navigateTo({
      url: '/pages/favorableRate/favorableRate?productId=' + type
    });
  },

  //点击控制购买商品的数量减少
  jian: function () {
    if (this.data.inputValue > 0) {
      this.setData({
        inputValue: this.data.inputValue - 1, // 将输入框的值赋给inputValue
        Totalprice: this.data.prices * (this.data.inputValue - 1)
      });
    }
    //判断当数量为0时则隐藏输入框
    if (this.data.inputValue < 1) {
      this.setData({
        hidden: true
      });
    }
    //获取用户id用来作为本地储存的key值
    this.delStorage();
    this.countprice();
    this.condition();
  },

  //计算商品价格和商品的数量并进行展示
  countprice: function () {
    var user_id = this.data.user_id;
    //获取并计算出商品的总价格进行保存
    var price = wx.getStorageSync(user_id);
    var total_price = 0,
      total_quantity = 0;
    for (var i = 0; i < price.length; i++) {
      total_price += price[i].cartprice * price[i].quantity;
      total_quantity += price[i].quantity;
    }
    this.setData({
      price: total_price.toFixed(2),
      bj_item: total_quantity
    })
  },

  //获取商品的数量
  countinputValue: function () {
    var user_id = this.data.user_id;
    //获取到本地数据存放在数组里面
    var cart = wx.getStorageSync(user_id);
    let cartID = this.data.type;
    let index = cart.findIndex(item => item.id == cartID);
    this.setData({
      inputValue: cart[index].quantity
    })
    //判断当数量大于0是则显示输入框
    if (this.data.inputValue > 0) {
      this.setData({
        hidden: false
      });
    }
  },

  //减少商品数量
  delStorage: function () {
    //获取用户id用来作为本地储存的key值
    var user_id = this.data.user_id;
    let cartID = this.data.list.id;
    let cartName = this.data.list.name;
    let cartPrice = this.data.list.price;
    let coverUrl = this.data.list.coverUrl;
    let quantity = this.data.inputValue;
    //获取了商品的id
    let ID = this.data.type;
    var cart = wx.getStorageSync(user_id);
    //查询到对应的商品并且更改商品数据
    let index = cart.findIndex(item => item.id == ID);
    if (quantity >= 0) {
      if (quantity > 0) {
        cart[index] = {
          id: cartID,
          name: cartName,
          cartprice: cartPrice,
          quantity: quantity,
          coverUrl: coverUrl
        };
      } else {
        cart.splice(index, 1);
      }
    }
    wx.setStorageSync(user_id, cart);
  },

  //将用户数据储存到本地,增加商品数量
  addStorage: function () {
    var app = getApp();
    console.log(this.data.inputValue)

    //获取用户id用来作为本地储存的key值
    var user_id = this.data.user_id;
    let cartID = this.data.list.id;
    let cartName = this.data.list.name;
    let specification = this.data.name
    let cartPrice = this.data.prices;
    let coverUrl = this.data.list.coverUrl;
    let quantity = this.data.inputValue;
    let productStatus = this.data.productStatus
    let categoriesId = this.data.categoriesId
    let specMultipleValue = this.data.specMultipleValue
    let canCoupon = this.data.canCoupon
    let mealType = this.data.mealType
    let week =this.data.week
    console.log(specMultipleValue)
    console.log(specification + specMultipleValue)
    this.setData({
      taoc: specification + '/' + specMultipleValue
    })
    console.log(this.data.taoc)
    const that =this
    wx.request({
      url: `https://199shq.com/api/menuManager/getMenuByProduct?isDeleted=${0}&categoriesId=${categoriesId}&time=${mealType}&week=${week}&setMenu=${specMultipleValue}`,
      method: 'GET',
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        console.log(res.data.data[0])
        that.setData({
          setMenus:res.data.data[0].data
        })
        console.log(that.data.setMenus)
      }
    });
    //获取了商品的id
    let ID = this.data.type;
    var list = [{
      id: cartID,
      name: cartName,
      cartprice: cartPrice,
      quantity: quantity,
      coverUrl: coverUrl,
      specification: specification,
      productStatus: productStatus,
      categoriesId: categoriesId,
      specMultipleValue: specMultipleValue,
      taoc: specification + specMultipleValue
    }];
    var cart = wx.getStorageSync(user_id);
    console.log(cart);
    console.log(wx.getStorageSync(user_id))
    if (cart.length > 0) {
      let index = cart.findIndex(item => item.id == ID);
      if (index != -1) {
        cart[index] = {
          id: cartID,
          name: cartName,
          cartprice: cartPrice,
          quantity: quantity,
          coverUrl: coverUrl,
          specification: specification,
          productStatus: productStatus,
          categoriesId: categoriesId,
          specMultipleValue: specMultipleValue,
          taoc: specification + specMultipleValue
        };
        wx.setStorageSync(user_id, cart);
        console.log(wx.getStorageSync(user_id))
      } else {
        cart.push({
          id: cartID,
          name: cartName,
          cartprice: cartPrice,
          quantity: quantity,
          coverUrl: coverUrl,
          specification: specification,
          productStatus: productStatus,
          specMultipleValue: specMultipleValue,
          canCoupon:canCoupon,
          categoriesId: categoriesId,
          taoc: specification + specMultipleValue,
        });
        wx.setStorageSync(user_id, cart);
        console.log(wx.getStorageSync(user_id))
      }
    } else {
      wx.setStorageSync(user_id, list);
      console.log(wx.getStorageSync(user_id))
    }
    // wx.setStorageSync(user_id, list);
  },
  onRadioChanges: function (e) {
    const value = e.detail.value;
    const that = this
    // 找到选中的数字
    const selectedItem = this.data.numberList.find(item => item.id === parseInt(value));

    if (selectedItem) {
      // 更新数字列表的选中状态
      const newList = this.data.numberList.map(item => ({
        ...item,
        checked: item.id === parseInt(value)
      }));
      // 更新数据
      this.setData({
        numberList: newList,
        specMultipleValue: selectedItem.namePlus
      });
      that.addStorage();
      that.countprice();
      that.condition();
      console.log(`选中数字: ${selectedItem.namePlus}`);
    }
  },
  //点击购买数量窗口的弹出
  createMaxs: function () {
    var that = this;
    const viey = that.data.viey
    if (!viey) {
      var toastText = '该商品已下架';
      wx.showToast({
        title: `${toastText}`,
        icon: '',
        duration: 2000
      });
      return;
    }
    const show = this.data.show
    if (show) {
      this.addCar()
    }
 
    this.setData({
      show: true
    });
    //调用关闭窗口函数方法
    let b = this.data.type;
    console.log(b)
    this.addStorage();
    // /api/tproduct/{id}

    wx.request({
      url: `https://199shq.com/api/tproduct/${b}`,
      method: 'GET',
      header: {
        'Content-Type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      success: function (res) {

        const checks = []
        const list = res.data.data
        if (res.data.data.specMultiple != undefined && res.data.data.specMultiple != '') {
          console.log(res.data.data.specMultiple)
          if (res.data.data.specMultiple !== '' && res.data.data.specMultiple !== undefined) {
            that.setData({
              hiddens: true,
            })

          }
          const numberList = res.data.data.specMultiple.split(',').map((num, index) => ({
            id: index + 1,
            namePlus: num,
            checked: index === 0 // 默认不选中
          }));
          console.log(numberList)
          that.setData({
            numberList: numberList,
            specMultipleValue: numberList[0].namePlus
          })
        }

        that.setData({
          categoriesId: res.data.data.categoriesId,
          // numberList: numberList
        })
        console.log(that.data.categoriesId)
        if (list.specification === 0) {
          var specification = false
          that.setData({
            // list: res.data.data,
            specification: specification,
            prices: list.price,
            inventory: list.stock,
            categoriesId: res.data.data.categoriesId,
            Totalprice:list.price
          })

          that.creates();
        } else {
          if (res.data.data.specName4 !== '' && res.data.data.specName4 !== null && res.data.data.specName4 !== undefined) {
            checks.push({
              namePlus: list.specName4,
              prices: list.specPrice4,
              Totalprice:list.specPrice4,
              inventory: list.specStock4,
              checked: true,
              id: 3,
              // name:
            }, {
              namePlus: list.specName3,
              prices: list.specPrice3,
              Totalprice:list.specPrice3,
              inventory: list.specStock3,
              id: 2
            }, {
              namePlus: list.specName2,
              prices: list.specPrice2,
              Totalprice:list.specPrice2,
              inventory: list.specStock2,
              id: 1
            }, {
              namePlus: list.specName,
              prices: list.specPrice,
              Totalprice:list.specPrice,
              inventory: list.specStock,
              id: 0
            })
            that.setData({
              // list: res.data.data,
              specification: true,
              prices: list.specPrice4,
              Totalprice:list.specPrice4,
              inventory: list.specStock4,
              checks: checks,
              name: list.specName4,
              // checksPlus:specName4
            })
            that.creates();
            console.log(checks)
            // this.create();
          } else if (res.data.data.specName3 !== '' && res.data.data.specName3 !== null && res.data.data.specName3 !== undefined) {
            checks.push({
              namePlus: list.specName3,
              prices: list.specPrice3,
              Totalprice:list.specPrice3,
              inventory: list.specStock3,
              checked: true,
              id: 2
            }, {
              namePlus: list.specName2,
              prices: list.specPrice2,
              Totalprice:list.specPrice2,
              inventory: list.specStock2,
              id: 1
            }, {
              namePlus: list.specName,
              prices: list.specPrice,
              Totalprice:list.specPrice,
              inventory: list.specStock,
              id: 0
            })
            that.setData({
              specification: true,
              // list: res.data.data,
              prices: list.specPrice3,
              Totalprice:list.specPrice3,
              inventory: list.specStock3,
              checks: checks,
              name: list.specName3,
            })
            console.log(checks)
            that.creates();
            // this.create();
          } else if (res.data.data.specName2 !== '' && res.data.data.specName2 !== null && res.data.data.specName2 !== undefined) {
            checks.push({
              namePlus: list.specName2,
              prices: list.specPrice2,
              Totalprice:list.specPrice2,
              inventory: list.specStock2,
              checked: true,
              id: 1
            }, {
              namePlus: list.specName,
              prices: list.specPrice,
              Totalprice:list.specPrice,
              inventory: list.specStock,
              id: 0
            })
            that.setData({
              specification: true,
              // list: res.data.data,
              prices: list.specPrice2,
              Totalprice:list.specPrice2,
              inventory: list.specStock2,
              checks: checks,
              name: list.specName2
            })
            console.log(checks)
            // this.create();
            that.creates();
          } else {
            checks.push({
              namePlus: list.specName,
              prices: list.specPrice,
              Totalprice:list.specPrice,
              inventory: list.specStock,
              checked: true,
              id: 0
            })
            that.setData({
              specification: true,
              // list: res.data.data,
              prices: list.specPrice,
              Totalprice:list.specPrice,
              inventory: list.specStock,
              checks: checks,
              name: list.specName
            })
            console.log(checks)
            that.creates();
            // this.create();
          }
        }
      },
    })

  },
  //点击购买数量窗口的弹出
  createMax: function () {
    var that = this;
    const viey = that.data.viey
    if (!viey) {
      var toastText = '该商品已下架';
      wx.showToast({
        title: `${toastText}`,
        icon: '',
        duration: 2000
      });
      return;
    }
    const show = this.data.show
    if (show) {
      console.log('进入')
      this.gpTo()
      return;
    }
    this.setData({
      show: true
    });
    //调用关闭窗口函数方法
    let b = this.data.type;
    console.log(b)
    this.addStorage();
    // /api/tproduct/{id}

    wx.request({
      url: `https://199shq.com/api/tproduct/${b}`,
      method: 'GET',
      header: {
        'Content-Type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      success: function (res) {

        const checks = []
        const list = res.data.data
        if (res.data.data.specMultiple != undefined && res.data.data.specMultiple != '') {
          console.log(res.data.data.specMultiple)
          if (res.data.data.specMultiple !== '' && res.data.data.specMultiple !== undefined) {
            that.setData({
              hiddens: true,
            })

          }
          const numberList = res.data.data.specMultiple.split(',').map((num, index) => ({
            id: index + 1,
            namePlus: num,
            checked: index === 0 // 默认不选中
          }));
          console.log(numberList)
          that.setData({
            numberList: numberList,
            specMultipleValue: numberList[0].namePlus
          })
        }

        that.setData({
          categoriesId: res.data.data.categoriesId,
          // numberList: numberList
        })
        console.log(that.data.categoriesId)
        if (list.specification === 0) {
          var specification = false
          that.setData({
            // list: res.data.data,
            specification: specification,
            prices: list.price,
            Totalprice:list.price,
            inventory: list.stock,
            categoriesId: res.data.data.categoriesId
          })

          that.creates();
        } else {
          if (res.data.data.specName4 !== '' && res.data.data.specName4 !== null && res.data.data.specName4 !== undefined) {
            checks.push({
              namePlus: list.specName4,
              prices: list.specPrice4,
              Totalprice:list.specPrice4,
              inventory: list.specStock4,
              checked: true,
              id: 3,
              // name:
            }, {
              namePlus: list.specName3,
              prices: list.specPrice3,
              Totalprice:list.specPrice3,
              inventory: list.specStock3,
              id: 2
            }, {
              namePlus: list.specName2,
              prices: list.specPrice2,
              Totalprice:list.specPrice2,
              inventory: list.specStock2,
              id: 1
            }, {
              namePlus: list.specName,
              prices: list.specPrice,
              Totalprice:list.specPrice,
              inventory: list.specStock,
              id: 0
            })
            that.setData({
              // list: res.data.data,
              specification: true,
              prices: list.specPrice4,
              Totalprice:list.specPrice4,
              inventory: list.specStock4,
              checks: checks,
              name: list.specName4,
              // checksPlus:specName4
            })
            that.creates();
            console.log(checks)
            // this.create();
          } else if (res.data.data.specName3 !== '' && res.data.data.specName3 !== null && res.data.data.specName3 !== undefined) {
            checks.push({
              namePlus: list.specName3,
              prices: list.specPrice3,
              Totalprice:list.specPrice3,
              inventory: list.specStock3,
              checked: true,
              id: 2
            }, {
              namePlus: list.specName2,
              prices: list.specPrice2,
              Totalprice:list.specPrice2,
              inventory: list.specStock2,
              id: 1
            }, {
              namePlus: list.specName,
              prices: list.specPrice,
              Totalprice:list.specPrice,
              inventory: list.specStock,
              id: 0
            })
            that.setData({
              specification: true,
              // list: res.data.data,
              prices: list.specPrice3,
              Totalprice:list.specPrice3,
              inventory: list.specStock3,
              checks: checks,
              name: list.specName3,
            })
            console.log(checks)
            that.creates();
            // this.create();
          } else if (res.data.data.specName2 !== '' && res.data.data.specName2 !== null && res.data.data.specName2 !== undefined) {
            checks.push({
              namePlus: list.specName2,
              prices: list.specPrice2,
              Totalprice:list.specPrice2,
              inventory: list.specStock2,
              checked: true,
              id: 1
            }, {
              namePlus: list.specName,
              prices: list.specPrice,
              Totalprice:list.specPrice,
              inventory: list.specStock,
              id: 0
            })
            that.setData({
              specification: true,
              // list: res.data.data,
              prices: list.specPrice2,
              Totalprice:list.specPrice2,
              inventory: list.specStock2,
              checks: checks,
              name: list.specName2
            })
            console.log(checks)
            // this.create();
            that.creates();
          } else {
            checks.push({
              namePlus: list.specName,
              prices: list.specPrice,
              Totalprice:list.specPrice,
              inventory: list.specStock,
              checked: true,
              id: 0
            })
            that.setData({
              specification: true,
              // list: res.data.data,
              prices: list.specPrice,
              Totalprice:list.specPrice,
              inventory: list.specStock,
              checks: checks,
              name: list.specName
            })
            console.log(checks)
            that.creates();
            // this.create();
          }
        }
      },
    })

  },
  creates: function () {
    const {
      inputValue,
      prices,
      list,
      inventory,
      Totalprice
    } = this.data;
    console.log("当前的商品详情")

    // this.data.inputValue = 1
    console.log(inputValue, inventory);
    if (inventory <= 0 || inputValue > inventory) {
      wx.showToast({
        title: '商品已没有库存',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    // 增加商品数量
    // this.setData({
    //   inputValue: inputValue + 1
    // });
    // 显示输入框
    if (inputValue === 0) {
      this.setData({
        hidden: false
      });
    }
    this.setData({
      Totalprice: Totalprice * inputValue
    });
    
    // 改变价格
    // this.setData({
    //   totalPrice: prices * (inputValue + 1)
    // });
    // 调用其他必要的函数
    this.addStorage();
    this.countprice();
    this.condition();
  },
  //点击控制购买商品的数量增加，点击加号同时对价格进行改变
  create: function () {
    const {
      inputValue,
      prices,
      list,
      inventory,

    } = this.data;
    console.log("当前的商品详情")

    // this.data.inputValue = 1
    console.log(inputValue, inventory);
    if (inventory === 0 || inputValue >= inventory) {
      wx.showToast({
        title: '商品已没有库存',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    console.log(inputValue)
    // 增加商品数量
    this.setData({
      inputValue: inputValue + 1
    });
    // 显示输入框
    if (inputValue === 0) {
      this.setData({
        hidden: false
      });
    }
    // 改变价格
    this.setData({
      Totalprice: prices * (inputValue + 1)
    });
    // 调用其他必要的函数
    this.addStorage();
    this.countprice();
    this.condition();
  },

  onRadioChange: function (e) {
    console.log(e)
    // 获取选中的值（id）  
    const selectedId = +e.detail.value; // 使用 + 转换为数字  

    // 获取选中的选项的下标  
    const selectedIndex = this.data.checks.findIndex(item => item.id === selectedId);
    console.log(selectedIndex)

    // 更新 checks 状态  
    const updatedChecks = this.data.checks.map((item, index) => ({
      ...item,
      checked: (index === selectedIndex) // 只有选中的项 checked 为 true  
    }));
    const newPrice = this.data.checks[selectedIndex].prices;
    const inputValue = this.data.inputValue
    const inventory = this.data.checks[selectedIndex].inventory;
    console.log(this.data.checks[selectedIndex])
    const specName = this.data.checks[selectedIndex].namePlus;
    // const pric = this.data.checks[selectedIndex].prices
    // console.log(specStock)
    // 更新数据  
    this.setData({
      checks: updatedChecks,
      prices: newPrice,
      Totalprice: inputValue*newPrice,
      inventory: inventory,
      name: specName
    });
    this.addStorage();
    console.log("Old Price:", this.data.prices);
  },

  //点击在购物车中减少对应的商品的数量
  decreaseQty: function (e) {
    var user_id = this.data.user_id;
    var list = this.data.list;
    var index = e.currentTarget.dataset.index;
    var cart = wx.getStorageSync(user_id);
    if (cart[index].quantity >= 1) {
      cart[index].quantity--;
      if (list.name == cart[index].name) {
        this.setData({
          inputValue: cart[index].quantity
        })
      }
      if (cart[index].quantity == 0) {
        //判断当数量为0时则隐藏输入框,并且删除该商品
        this.setData({
          hidden: true
        });
        cart.splice(index, 1);
      }
    } else {

    }
    wx.setStorageSync(this.data.user_id, cart);
    this.setData({
      cart: cart
    })
    this.countprice();
    //判断如果购物车中不存在商品了，则购物车回复原样
    this.condition();
    let condition = this.data.condition;
    if (condition === false) {
      this.hideModal();
    }
  },
  // 判断购物车中是否存在商品
  condition: function () {
    var user_id = this.data.user_id;
    var cart = wx.getStorageSync(user_id);
    //判断cart中是否存在数据
    if (cart.length > 0 && cart[0] != null && cart[0] != undefined) {
      this.setData({
        condition: true
      })
    } else {
      this.setData({
        condition: false
      })
    }
  },

  //点击在购物车中增加对应的商品的数量
  increaseQty: function (e) {
    let quantity;
    var user_id = this.data.user_id;
    var index = e.currentTarget.dataset.index;
    var cart = wx.getStorageSync(user_id);
    var list = this.data.list;
    cart[index].quantity++;
    wx.setStorageSync(this.data.user_id, cart);
    this.setData({
      cart: cart
    })
    this.countprice();
    if (list.name == cart[index].name) {
      this.setData({
        inputValue: cart[index].quantity
      })
    }
  },

  //清空购物车的所有商品
  delcart: function () {
    var that = this;
    // 提示框
    wx.showModal({
      title: '提示',
      content: '是否确定清空购物车？',
      success: function (res) {
        if (res.confirm) {
          var user_id = that.data.user_id;
          var cart = wx.getStorageSync(user_id);
          cart.splice(0, cart.length);
          wx.setStorageSync(that.data.user_id, cart);
          that.hideModal();
          that.countprice();
          that.condition();
          that.setData({
            inputValue: 0
          })
          //清空购物车并且隐藏减号
          that.setData({
            hidden: true
          });
        } else {

        }
      }
    })
  },

  //用来绑定输入框里面的双向绑定
  handleInput: function (e) {
    let value = e.detail.value;
    let prices = this.data.prices
    
    // 处理空值情况
    if (value === '') {
      this.setData({ inputValue: 0 , Totalprice:0});
      return;
    }
    
    // 处理首位为0且长度超过1的情况（去掉首位0）
    if (value.length > 1 && value[0] === '0') {
      // 连续多个0的情况（如"000123"处理为"123"）
      value = value.replace(/^0+/, '');
      // 若处理后为空（如"0000"），保留一个0
      if (value === '') {
        value = '0';
      }
    }
   
    this.setData({ inputValue: value,Totalprice:prices * value });
    this.addStorage();
    console.log(this.data.inputValue)
    // 禁止输入框编辑（需在wxml中配合disabled属性实现）
  },

  //onload方法在页面加载完成时开始执行,并且加载数据库数据
  handleImageTap: function (e) {
    console.log("打印了点击商品的轮播图放大")
    var src = e.currentTarget.dataset.src; // 获取图片地址
    console.log(e.currentTarget.dataset.src)
    //关闭窗口
    // this.closePopup();
    wx.previewImage({
      current: src, // 当前显示图片的链接
      urls: [src] // 需要预览的图片链接列表，这里只有一张图片，所以只传入一个链接
    })
  },
  getdata: function () {
    var that = this;
    let b = this.data.type;
    wx.request({
      url: `https://199shq.com/api/tproduct/${b}`,
      method: 'GET',
      header: {
        'Content-Type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      success: function (res) {
        console.log(res.data.data);
        console.log(res.data.data.id);
        var list = res.data.data;
        const categoriesId = res.data.data.categoriesId
        that.setData({
          canCoupon: res.data.data.canCoupon,
        })
        // 判断商品状态
        if (res.data.data.productStatus == 0) {
          wx.showToast({
            title: '商品已下架',
            icon: '',
            duration: 2000
          });
          that.setData({
            viey: false,
          })
          return;
        }

        // 提取餐次信息
        let mealType = '';
        if (list && list.name) {
          const name = list.name;
          if (name.includes('早餐')) {
            mealType = '早餐';
          } else if (name.includes('午餐')) {
            mealType = '午餐';
          } else if (name.includes('晚餐')) {
            mealType = '晚餐';
          }
        }

        // 获取明天是星期几
        const weekdays = ['日', '一', '二', '三', '四', '五', '六'];
        const tomorrow = new Date();
        tomorrow.setDate(tomorrow.getDate() + 1);
        const dayOfWeek = weekdays[tomorrow.getDay()];

        console.log(`提取的餐次: ${mealType}`);
        console.log(`明天是星期${dayOfWeek}`);
        const week = `星期${dayOfWeek}`
        console.log(week)
        // 处理商品数据
        if (list == null) {
          var toastText = '数据获取失败';
          wx.showToast({
            title: toastText, // 修正此处的变量引用
            icon: '',
            duration: 2000
          });
        } else {
          const productList = [];
          productList.push({
            coverUrls: [
              list.coverUrl,
              list.coverUrl2,
              list.coverUrl3,
              list.coverUrl4,
              list.coverUrl5
            ],
          });

          console.log("这是商品详情页面图片");
          console.log(productList);

          that.setData({
            list: res.data.data,
            productList: productList,
            productStatus: res.data.data.productStatus,
            mealType: mealType, // 保存提取的餐次
            dayOfWeek: dayOfWeek, // 保存明天的星期几
            categoriesId:categoriesId,
            week:week,
          });

          // 现在可以将mealType和dayOfWeek传递给其他接口
          // 例如：在后续请求中添加这两个参数
          console.log(dayOfWeek)
          console.log(week)
          wx.request({
            url: `https://199shq.com/api/menuManager/getMenuByProduct?isDeleted=${0}&categoriesId=${categoriesId}&time=${mealType}&week=${week}`,
            method: 'GET',
            header: {
              'content-type': 'application/json'
            },
            success: function (res) {

              let mealList = []; // 在回调函数顶部声明变量
              that.setData({
                setMenu:res.data.data
              })
              console.log(that.data.setMenu)
              // if (mealType === '') {
              //   // 处理mealType为空的情况（合并多个数组）
              //   const dataList = res.data.data.dataList[0].data;
              //   for (let i = 0; i < dataList.length; i++) {
              //     if (Array.isArray(dataList[i].data)) {
              //       mealList = mealList.concat(dataList[i].data);
              //     }
              //   }
              // } else {
              //   // 处理mealType不为空的情况（直接获取数据）
              //   mealList = res.data.data.dataList[0].data[0].data || [];
              // }

              // // 更新数据到页面实例
              // that.setData({
              //   mealList,
              //   isLoading: false
              // }, () => {
              //   // 数据加载完成后初始化滚动
              //   that.initDisplayList();
              //   if (mealList.length > 1) {
              //     that.startAutoScroll();
              //   }
              // });


              // 处理分类数据...
            }
          });
        }
      }
    });
  },
  // 初始化显示列表
  initDisplayList() {
    const {
      mealList
    } = this.data;

    if (mealList.length <= 1) {
      this.setData({
        displayList: mealList
      });
      return;
    }

    // 修复：正确复制整个数组，形成 [A,B,C,A,B,C] 结构
    const displayList = [...mealList];

    this.setData({
      displayList
    });
  },

  // 开始自动滚动
  startAutoScroll() {
    this.timer = setInterval(() => {
      this.scrollToNext();
    }, this.data.interval);
  },

  // 滚动到下一个菜品
  scrollToNext() {
    const {
      displayList,
      currentIndex,
      itemHeight,
      mealList
    } = this.data;
    const realCount = mealList.length; // 真实数据量

    // 计算下一个索引
    let nextIndex = currentIndex + 1;

    // 当滚动到第二组数据的末尾时，重置回第一组的对应位置
    if (nextIndex >= displayList.length) {
      nextIndex = nextIndex - realCount;
    }

    // 更新偏移量（每次滚动一个菜品高度）
    this.setData({
      currentIndex: nextIndex,
      currentOffset: nextIndex * itemHeight,
      transition: 'transform 0.5s ease-in-out'
    });
  },

  onUnload() {
    clearInterval(this.timer);
  },
  onLoad: function (options) {
    // 获取门店id
    let type = options.type;
    console.log("页面加载获取得门店id" + options);
    this.setData({
      type: type,
      showVideo: false // 默认隐藏视频
    });
    // 调用获取商品详情的方法
    this.getdatadetail();
  },

  // 根据商品id获取对应商品视频
  getVideoUrl: function () {
    var that = this;
    let b = this.data.type;
    console.log(b);
    wx.request({
      url: `https://199shq.com/api/productVideo/${b}`,
      method: 'GET',
      header: {
        'Content-Type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      success: function (res) {
        console.log(res.data);
        if (res.data && res.data.data) {
          var videoUrl = res.data.data.videoName1;
          console.log(videoUrl); // 在这里打印 videoUrl
          if (videoUrl == null) {
            var toastText = '';
            wx.showToast({
              title: toastText,
              icon: 'none',
              duration: 2000
            });
            that.setData({
              showVideo: false // 视频链接不存在，隐藏视频
            });
          } else {
            that.setData({
              videoUrl: videoUrl,
              showVideo: true // 视频链接存在，显示视频
            }, function () {
              // 播放视频
              that.videoContext.play();
            });
          }
        } else {
          // var toastText = '该商品没有配套视频';
          wx.showToast({
            title: toastText,
            icon: 'none',
            duration: 2000
          });
          that.setData({
            showVideo: false // 视频链接不存在，隐藏视频
          });
        }
      },
      fail: function (err) {
        console.log('请求接口失败:', err);
      }
    });
  },
  gj: function () {

  },
  //获取商品详情的api
  getdatadetail: function () {
    var that = this;
    let b = this.data.type;
    console.log("获取商品详情的api:" + b);
    wx.request({
      url: `https://199shq.com/api/tproduct/details/${b}`,
      method: 'GET',
      header: {
        'Content-Type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      success: function (res) {
        console.log("商品详情的api对象" + res.data.data);
        var list = res.data.data;
        console.log(list[0]);
        if (list == null) {
          var toastText = '数据获取失败';
          wx.showToast({
            title: `${toastText}`,
            icon: '',
            duration: 2000
          });
        } else {

          that.setData({
            detail: list[0]
          })
        }
      }
    })
    // 请求当前商品详情下所有用户评价内容
    wx.request({
      url: `https://199shq.com/api/wxComment/getComment?productId=` + b,
      method: 'GET',
      header: {
        'Content-Type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      success: function (res) {
        var list = res.data.data.commentEntities;
        let goodRatingPercentage = res.data.data.goodRatingPercentage;

        goodRatingPercentage = goodRatingPercentage.toFixed(2);
        if (list == null) {
          var toastText = '数据获取失败';
          wx.showToast({
            title: `${toastText}`,
            icon: '',
            duration: 2000
          });
        } else {
          const leng = list.length;
          that.setData({
            leng: leng,
            percent: goodRatingPercentage
          });
          if (list.length > 2) {
            list = list.slice(list.length - 2);
            that.setData({
              orderList: list
            })
          }

        }
        console.log("所有用户的评价内容")
        console.log(that.data.orderList);
      }
    })

  },

  showPopup: function () {
    console.log("购物车被点击了")
    wx.switchTab({
      url: '/pages/moog/moog'
    });
    // let condition = this.data.condition;
    // if (condition) {
    //   this.setData({
    //     popupBottom: 0
    //   });
    //   this.setData({
    //     z_index: 0
    //   })
    //   //点击时，使图标上移
    //   const animation = wx.createAnimation({
    //     duration: 300,
    //     timingFunction: 'ease-in-out',
    //   });
    //   animation.translateY(-170).step();

    //   this.setData({
    //     animation: animation.export(),
    //   });
    //   //点击开启背景变灰
    //   this.setData({
    //     hidden_bg: false
    //   });
    //   var user_id = this.data.user_id;
    //   var cart = wx.getStorageSync(user_id);
    //   this.setData({
    //     cart: cart
    //   })
    // }
  },

  //点击灰暗区域隐藏
  hideModal: function () {
    this.setData({
      popupBottom: -100
    });
    this.setData({
      z_index: -1
    })
    //点击时，使图标下移
    const animation = wx.createAnimation({
      duration: 300,
      timingFunction: 'ease-in-out',
    });
    animation.translateY(170).step();

    this.setData({
      animation: animation.export(),
    });
    //点击关闭背景变灰
    this.setData({
      hidden_bg: true
    });
  },

  hidePopup: function () {
    this.setData({
      popupBottom: -100
    });
  },

  //去结算跳转，跳转到去结算页面
  gpTo() {
    var that = this;

    
    var app = getApp();
    if (!app.globalData.userInfo) {
      // // 如果用户未授权登录，则跳转到登录页面
      // wx.navigateTo({
      //   url: '/pages/about/about'
      // });
      // 如果用户未授权登录，则弹出提示框
      wx.showModal({
        title: '提示',
        content: '请先授权登录账号',
        showCancel: false,
        success: function (e) {
          if (e.confirm) {
            wx.navigateTo({
              url: '/pages/login/login'
            });
          }
        }
      });

    } else { //如果登录成功了则将用户id储存进入
      // console.log(app.globalData.userInfo);
      // console.log(this.data.user_id);

      const inputValue = this.data.inputValue
      console.log(inputValue)
      const inventory = this.data.inventory
      console.log(inventory)
      const hess = this.data.hiddens
      if (inventory <= 0 ) {
        wx.showToast({
          title: '暂无库存', // 错误提示内容  
          icon: 'none', // 图标类型，可以是 'success', 'loading', 'none'  
          duration: 2000 // 提示持续时间，单位为 ms  
        });
        return;
      }
      //inputValue为输入值，inventory为库存值
      if (inputValue <= 0) {
        wx.showToast({
          title: '库存不能小于等于0', // 错误提示内容  
          icon: 'none', // 图标类型，可以是 'success', 'loading', 'none'  
          duration: 2000 // 提示持续时间，单位为 ms  
        });
      }else if (inventory < inputValue) {
        wx.showToast({
          title: '已超过最大库存', // 错误提示内容  
          icon: 'none', // 图标类型，可以是 'success', 'loading', 'none'  
          duration: 2000 // 提示持续时间，单位为 ms  
        });
      }else {
        var storeID = this.data.storeID;
        var app = getApp();
        var prices = this.data.prices
        var name = this.data.name
        var productStatus = this.data.productStatus
        var categoriesId = this.data.categoriesId
        var specMultipleValue = this.data.specMultipleValue
        var canCoupon = this.data.canCoupon
        console.log(this.data)
        // 如果用户已授权登录，则跳转到对应页面
        app.globalData.cat_ID = [];
        console.log('进入结算')
        wx.navigateTo({
          url: `/pages/cesi2/cesi2?value=${storeID}&prices=${prices}&name=${name}&productStatus=${productStatus}&categoriesId=${categoriesId}&specMultipleValue=${specMultipleValue}&canCoupon=${canCoupon}`
        });
      }
    }
  },

  //验证用户是否登录如果未登录则跳转去登录页面
  verify: function () {
    var that = this;
    var app = getApp();
    if (!app.globalData.userInfo) {
      // // 如果用户未授权登录，则跳转到登录页面
      // wx.navigateTo({
      //   url: '/pages/about/about'
      // });
      // 如果用户未授权登录，则弹出提示框
      // wx.showModal({
      //   title: '提示',
      //   content: '请先授权登录账号',
      //   showCancel: false,
      //   success: function (e) {
      //     if (e.confirm) {
      //       wx.navigateTo({
      //         url: '/pages/login/login'
      //       });
      //     }
      //   }
      // });
      that.setData({
        user_id: String(app.globalData.userInfo.wxUserId)
      })
    } else { //如果登录成功了则将用户id储存进入
      // console.log(app.globalData.userInfo);
      that.setData({
        user_id: String(app.globalData.userInfo.wxUserId)
      })
      // console.log(this.data.user_id);
    }
  },

  //点击获取到该商品的分销二维码
  goodsDis: function () {
    var app = getApp();
    var value = this.data.type;
    var value2 = this.data.storeID;
    //跳转到展示二维码页面
    wx.navigateTo({
      url: `/pages/erweima/erweima?value=${value}&value2=${value2}`
    });
  },

  //判断用户是否登录，并且对于相应的东西进行相应的操作
  isLogin: function () {
    //实例化全局变量
    var userInfo = getApp().globalData.userInfo;
    //对全局进行判断
    if (!userInfo) {
      // 如果用户未授权登录，则弹出提示框
      wx.showModal({
        title: '提示',
        content: '请先授权登录账号',
        showCancel: false,
        success: (res) => {
          // 用户点击确定
          if (res.confirm) {
            // 跳转到登录页
            wx.navigateTo({
              url: '/pages/login/login'
            });
          }
        }
      });
    }
  },

  //获取门店的背景图片和头像
  getMendian: function () { //定义函数名称
    var that = this;
    let b = this.data.storeID;
    console.log(this.data)
    wx.request({
      url: `https://199shq.com/api/stores/${b}`,
      method: 'GET',
      header: {
        'Content-Type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      success: function (res) {
        console.log(res.data);
        var list = res.data.data;
        if (list == null) {
          var toastText = '数据获取失败';
          wx.showToast({
            title: `${toastText}`,
            icon: '',
            duration: 2000
          });
          that.setData({
            viey: false
          })
        } else {
          that.setData({
            mendian: res.data.data,
            specMultiple: that.data.list.specMultiple
          })
          console.log(that.data)
          console.log(that.data.list.specMultiple)
        }
      }
    })
  },

  //点击添加到购物车方法
  addCar: function () {

    var that = this;
    const viey = that.data.viey
    const {
      inputValue,
      prices,
      list,
      inventory,
      Totalprice
    } = this.data;
    console.log("当前的商品详情")

    // this.data.inputValue = 1
    console.log(inputValue, inventory);
    if (inventory <= 0 || inputValue > inventory) {
      wx.showToast({
        title: '商品已没有库存',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    if (!viey) {
      var toastText = '该商品已下架';
      wx.showToast({
        title: `${toastText}`,
        icon: '',
        duration: 2000
      });
      return;
    }
    console.log('进入' + that.data.mendian)

    //先从本地获取到购车里面的商品信息
    var app = getApp();
    //获取到微信userid
    var user_id = String(app.globalData.userInfo.wxUserId);
    var cart = wx.getStorageSync(user_id);
    console.log("用户id：" + cart);
    console.log(wx.getStorageSync(user_id));
    //将规格添加到购物车
    //arr获取到checked应该是true
    // let arr = this.data.checks;
    // //arrsChecks为null
    // let arrsChecks = this.data.checksPlus;
    // console.log(arr);
    // console.log(arrsChecks);
    // if (arrsChecks == '') {
    //   wx.showToast({
    //     title: '请选择规格',
    //     icon: 'none'
    //   });
    //   return;
    //   //如果规格有数据并且数量为0，点击进行加入购物车
    // } else if (cart.length == 0) {
    //   wx.showToast({
    //     title: '请选择要添加的商品',
    //     icon: 'none'
    //   });
    //   return;
    // }
    console.log( that.data.mendian);
    //获取到门店的信息
    var storeid = this.data.storeID;
    var storeName = that.data.mendian.name;
    var storeurl = that.data.mendian.storeTximgUrl;
    var categoriesId = that.data.categoriesId
    console.log("获取到门店的信息" + storeid, storeName, storeurl);
    //循环遍历，将不同的商品遍历生成不同的购物车订单
    for (var i = 0; i < cart.length; i++) {
      console.log(cart);
      var goodid = cart[i].id;
      var goodname = cart[i].name;
      var goodprice = cart[i].cartprice;
      var goodurl = cart[i].coverUrl;
      var goodnum = cart[i].quantity;
      var specification = cart[i].specification;
      var specMultipleValue = cart[i].specMultipleValue
      console.log(specMultipleValue)
      //规格
      wx.request({
        url: `https://199shq.com/api/shoppingCart`,
        method: 'POST',
        header: {
          'Content-Type': 'application/json',
          'token': wx.getStorageSync('token')
        },
        data: {
          "wxUserId": user_id,
          "storeId": storeid,
          "goodsId": goodid,
          "goodsName": goodname,
          "specMultipleValue": specMultipleValue,
          //规格
          // "specification": specifications,
          "goodsPrice": goodprice,
          "goodsUrl": goodurl,
          "goodsNumber": goodnum,
          "storeName": storeName,
          "storeUrl": storeurl,
          "goodsSpecName": specification,
          "categoriesId": categoriesId
        },
        success: function (res) {
          console.log("res：" + res.data);
          if (res.data.code == 200) {
            wx.showToast({
              title: `加入成功`,
              icon: 'none'
            });
            var user_id = that.data.user_id;
            //将选择的规格信息数据添加到购物车Cart当中

            var cart = wx.getStorageSync(user_id);
            cart.splice(0, cart.length);
            // wx.setStorageSync(that.data.user_id, cart);
            that.hideModal();
            that.countprice();
            that.condition();
            that.setData({
              inputValue: 1
            })
            //清空购物车并且隐藏减号
            //清理的的时候添加一些隐藏样式，并且修改显示的东西
            that.setData({
              hidden: true
            });
          }
        }
      })
    }
    //调用窗口关闭
    // this.closePopup();
  },

  // deleteSelete:function(){
  //   //触发父组件中的方法
  //   this.triggerEvent('deleteSelected')
  //   //根据需求看是否需要隐藏弹出框
  //   this.hideModal()
  // },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let that = this;
    that.removeStorageSync()
    this.verify();
    console.log(options);
    console.log("监听页面加载" + options.inviteid);
    var userInfo = wx.getStorageSync('userInfo');
    if (options.inviteid != undefined) {
      if (!userInfo) {
        wx.showToast({
          title: '请先登录',
          icon: 'none', // 不显示图标，可设置为 'success'、'loading' 等
          duration: 2000 // 提示框显示时长，单位为毫秒
        })
        // this.bindGetUserInfo();
        return;
        // console.log('既然你')
      }
      // const data ={
      //   inviteWxUserId:options.inviteid,
      //   userId:userInfo.wxUserId
      // }
      wx.request({
        url: `https://199shq.com/api/wxuser/setInviteWxUserId?inviteWxUserId=${options.inviteid}&userId=${userInfo.wxUserId}`,
        method: 'POST',
        // data:data,
        header: {
          'Content-Type': 'application/json',
          'token': wx.getStorageSync('token')
        },
        success: function (res) {
          // 请求成功处理逻辑
          console.log(res)
          if (res.data.code) {
            wx.showModal({
              title: `${res.data.data.msg}`,
              icon: 'success',
              duration: 2000,
              showCancel: false,
            });
            getApp().globalData.inviteid = res.data.data.inviteWxUserId;
          }

          // 根据返回的结果进行相应的操作
        },
        fail: function (error) {
          wx.showToast({
            title: '绑定失败',
            icon: 'none',
            duration: 2000
          });
          // 请求失败处理逻辑
          // console.error('退款申请失败', error);
        }
      });
    } else {
      console.log('今日')
      wx.request({
        url: `https://199shq.com/api/wxuser/queryWxUserId/${userInfo.wxUserId}`,
        method: 'GET',
        // data:data,
        header: {
          'Content-Type': 'application/json',
          'token': wx.getStorageSync('token')
        },
        success: function (res) {
          // 请求成功处理逻辑

          console.log(res)
          if (res.data.code == 200) {
            console.log("请求成功处理逻辑")
            // wx.showModal({
            //   title: `${res.data.data.msg}`,
            //   icon: 'success',
            //   duration: 2000,
            //   showCancel: false,
            // });
            if (res.data.data.inviteWxUserId != undefined) {
              console.log("请求成功处理逻辑")
              getApp().globalData.inviteid = res.data.data.inviteWxUserId;
            }

            console.log()
          }

          // 根据返回的结果进行相应的操作
        },
        fail: function (error) {
          wx.showToast({
            title: '绑定失败',
            icon: 'none',
            duration: 2000
          });
          // 请求失败处理逻辑
          // console.error('退款申请失败', error);
        }
      });
      console.log("邀请人id的全局变量" + getApp().globalData.inviteid);
    }
    console.log("邀请人id的全局变量" + getApp().globalData.inviteid);

    that.setData({
      type: options.value,
      storeID: options.value2,
    });
    that.condition();
    that.getdata();
    that.getdatadetail();
    that.countprice();
    that.countinputValue();
    that.isLogin();
    that.getStoreCoupon();

  },

  /**
   * 优惠券的弹出窗口展示
   */
  showPopup1() {
    this.setData({
      showMask: true,
      popupBottom: 0, // 弹窗底部移动到可见位置
      popupHeight: 500
    })
  },
  hidePopup() {
    this.setData({
      showMask: false,
      popupBottom: -200, // 弹窗底部移动到可见位置
      popupHeight: 0
    })
  },

  // 查询门店优惠券
  getStoreCoupon: function () {
    let storeID = this.data.storeID;
    console.log("门店id:" + storeID);
    wx.request({
      url: `https://199shq.com/api/coupons/store/${storeID}`,
      method: 'GET',
      header: {
        'Content-Type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      success: (res) => {
        console.log(res.data.data);
        this.setData({
          voucherText: res.data.data // 更新voucherText
        });
      }
    })
  },

  /**
   * 处理领取优惠券 现金券
   */
  handleButtonClick: function (e) {
    // 处理按钮点击事件的逻辑
    console.log(this.data.voucherText);

    // 可以在这里执行其他操作或调用其他函数
    const dataset = e.currentTarget.dataset;
    const id = dataset.id;
    var that = this;
    //先从本地获取到购车里面的商品信息
    var app = getApp();
    //获取到微信userid
    var user_id = String(app.globalData.userInfo.wxUserId);

    console.log("用户id：" + user_id);
    wx.request({
      url: 'https://199shq.com/api/couponReceive',
      method: 'POST',
      header: {
        'Content-Type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      data: {
        "userId": user_id,
        "templateId": id
      },
      success: (res) => {
        console.log(res.data.data);
        that.getStoreCoupon();
      }
    })

  },
  handleButtonClicks: function (e) {
    // 处理按钮点击事件的逻辑  满减券
    console.log("满减券按钮被点击了");
    const dataset = e.currentTarget.dataset;
    const id = dataset.id;
    var that = this;
    //先从本地获取到购车里面的商品信息
    var app = getApp();
    //获取到微信userid
    var user_id = String(app.globalData.userInfo.wxUserId);

    console.log("用户id：" + user_id);
    wx.request({
      url: 'https://199shq.com/api/couponReceive',
      method: 'POST',
      header: {
        'Content-Type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      data: {
        "userId": user_id,
        "templateId": id
      },
      success: (res) => {
        console.log(res.data.data);
        that.getStoreCoupon();
      }
    })

  },
  // 折扣券
  handleButtonClicking: function (e) {
    const dataset = e.currentTarget.dataset;
    const index = dataset.index;
    const id = dataset.id;
    console.log('点击的项目索引:', index, '点击的项目ID:', id);
    // 根据index或id进行后续操作...
    var that = this;
    //先从本地获取到购车里面的商品信息
    var app = getApp();
    //获取到微信userid
    var user_id = String(app.globalData.userInfo.wxUserId);

    console.log("用户id：" + user_id);
    wx.request({
      url: 'https://199shq.com/api/couponReceive',
      method: 'POST',
      header: {
        'Content-Type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      data: {
        "userId": user_id,
        "templateId": id
      },
      success: (res) => {
        console.log(res.data.data);
        that.getStoreCoupon();
      }
    })
  },
  removeStorageSync: function () {
    var app = getApp();
    var user_id = String(app.globalData.userInfo.wxUserId);
    // 清除缓存数据
    wx.removeStorageSync(user_id);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    // 调用获取商品视频的方法
    this.getVideoUrl();
    // 获取视频组件
    this.videoContext = wx.createVideoContext('videoPlayer');
    // 在页面加载时进行初始化，券展示
    //  this.setData({
    //   voucherText: ["券 现金券20", "券 折扣券50%","券 免费配送券"] // 设置要填充的内容数组
    // });
    console.log("券展示：" + this.data.voucherText);
    this.getStoreCoupon();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.countprice();
    let that = this;
    //获取到门店的信息
    that.getMendian();
    that.verify();
    that.countinputValue();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    console.log('进入返回')
    this.setData({
      inputValue: 0 // 将输入框的值赋给inputValue
    });
    this.delStorage();
    this.countprice();
    this.condition();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})